<%+header%>
<h2 name="content"><%:Attended Sysupgrade%></h2>
<div  class="container">
	<div style="display: none" id="update_info" class="alert-message info">
	</div>
	<div style="display: none" id="update_error" class="alert-message danger">
	</div>
</div>
<input class="cbi-button" value="search for updates" onclick="update_request()" type="button" id="update_button">

<script type="text/javascript">

latest_release = "";
data = {};
ubus_counter = 1
origin = document.location.href.replace(location.pathname, "")
ubus_url = origin + "/ubus/"

// requests to the update server
function server_request(request_dict, path, callback) {
	url = data.update_server + "/" + path
	request_dict.distro = data.release.distribution;
	request_dict.target = data.release.target.split("\/")[0];
	request_dict.subtarget = data.release.target.split("\/")[1];
	request_dict.packages = data.packagelist;
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("POST", url, true);
	xmlhttp.setRequestHeader("Content-type", "application/json");
	xmlhttp.send(JSON.stringify(request_dict));
	xmlhttp.onerror = function(e) {
		update_error("update server down")
	}
	xmlhttp.addEventListener('load', function(event) {
		callback(xmlhttp)
	});
}

// requests ubus via rpcd
function ubus_request(command, argument, params, callback) {
	// perform login if ubus_rpc_session is empty
	var request_data = '{ "jsonrpc": "2.0", "id": ' + ubus_counter + ', "method": "call", "params": [ "'+ data["ubus_rpc_session"] +'", "' + command + '", "' + argument + '", ' + params + ' ] }'
	ubus_counter++
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("POST", ubus_url, true);
	xmlhttp.setRequestHeader("Content-type", "application/json");
	xmlhttp.onerror = function(e) {
		setTimeout(back_online, 5000)
	}
	xmlhttp.addEventListener('load', function(event) {
		if(command === "uci") {
			ubus_request_callback_uci(xmlhttp, callback)
		} else {
			ubus_request_callback(xmlhttp, callback)
		}
	});
	xmlhttp.send(request_data);
}

// handle ubus_requests, set variables or perform functions
function ubus_request_callback(response_object, callback) {
	if(response_object.status === 200) {
		console.log(callback)
		if(typeof callback === "string") {
			response_json = JSON.parse(response_object.responseText).result[1]
			data[callback] = response_json[callback]
		} else {
			callback(response_object)
		}
	} else {
		console.log(respons_object.responseText)
	}
}

function ubus_request_callback_uci(response_object, callback) {
	if(response_object.status === 200) {
		console.log(callback)
		response_json = JSON.parse(response_object.responseText).result[1].value
		data[callback] = response_json
	} else {
		console.log(respons_object.responseText)
	}
}

// initial setup, get system information
function setup() {
	data["ubus_rpc_session"] = "<%=luci.dispatcher.context.authsession%>"
	ubus_request("packagelist", "list", '{  }', "packagelist")
	ubus_request("system", "board", '{  }', "release")
	ubus_request("system", "board", '{  }', "board_name")
	ubus_request("uci", "get", '{"config": "attendedsysupgrade", "section": "@settings[0]", "option": "update_server"}', "update_server")
}

// shows notification if update is available
function update_info(info_output) {
	document.getElementById("update_info").style.display = "block";
	document.getElementById("update_info").innerHTML = info_output;
}

function update_error(error_output) {
	document.getElementById("update_error").style.display = "block";
	document.getElementById("update_error").innerHTML = error_output;
	document.getElementById("update_info").style.display = "None";
}

// asks server for news updates, actually only based on relesae not packages
function update_request() {
	console.log("update_request")
	request_dict = {}
	request_dict.version = data.release.version;
	server_request(request_dict, "update-request", update_request_callback)
}

function update_request_callback(response_object) {
	if (response_object.status === 500) {
		// python crashed
		update_error("internal server error, please try again later")
		console.log("update server issue")
	} else if (response_object.status === 502) {
		// python part offline
		update_error("internal server error, please try again later")
		console.log("update server issue")
	} else if (response_object.status === 503) {
		// handle overload
		update_error("server overloaded, retry in 5 minutes")
		console.log("server overloaded")
		setTimeout(update_request, 300000)
	} else if (response_object.status === 201) {
		update_info("imagebuilder not ready, please wait")
		console.log("setting up imagebuilder")
		setTimeout(update_request, 5000)
	} else if (response_object.status === 204) {
		// no updates
		update_info("no updates available")
	} else if (response_object.status === 400) {
		// bad request
		console.log(response_object.responseText)
		response_object_content = JSON.parse(response_object.responseText)
		update_error(response_object_content)
	} else if (response_object.status === 200) {
		// new release/updates
		response_object_content = JSON.parse(response_object.responseText)
		update_request_200(response_object_content)
	}
}

function back_online() {
	ubus_request("session", "login", '{  }', back_online_callback)
}

function back_online_callback(response_object) {
	if (response_object.status != 200) {
		setTimeout(back_online, 5000)
	} else {
		update_info("upgrade successfull!")
		document.getElementById("update_button").value = "reload page";
		document.getElementById("update_button").onclick = function() { location.reload(); }
	}

}

function update_request_200(response_content) {
	info_output = ""
	if(response_content.version != undefined) {
		info_output += "new update available. from " + data.release.version + " to " + response_content.version
		latest_version = response_content.version;
	}
	if(response_content.packages != undefined) {
		info_output += "package updates available"
	}
	update_info(info_output)
	document.getElementById("update_button").value = "request image";
	document.getElementById("update_button").onclick = image_request;
}

// request the image, need merge with update_request
function image_request() {
	console.log("image_request")
	request_dict = {}
	request_dict.version = latest_version;
	request_dict.board = data.board_name
	server_request(request_dict, "image-request", image_request_handler)
}

function image_request_handler(response) {
	if (response.status === 400) {
		response_content = JSON.parse(response.responseText)
		update_error(response_content.error)
	} else if (response.status === 500) {
		image_request_500()
	} else if (response.status === 503) {
		update_error("please wait. server overloaded")
		// handle overload
		setTimeout(image_request, 30000)
	} else if (response.status === 201) {
		response_content = JSON.parse(response.responseText)
		if(response_content.queue != undefined) {
			// in queue
			update_info("please wait. you are in queue position " + response_content.queue)
			console.log("queued")
		} else {
			update_info("imagebuilder not ready, please wait")
			console.log("setting up imagebuilder")
		}
		setTimeout(image_request, 5000)
	} else if (response.status === 206) {
		// building
		console.log("building")
		update_info("building image")
		setTimeout(image_request, 5000)
	} else if (response.status === 200) {
		// ready to download
		response_content = JSON.parse(response.responseText)
		update_info("image created")
		document.getElementById("update_button").value = "download and flash"
		document.getElementById("update_button").onclick = function() {download_image(response_content.url); }
	}
}


// uploads received blob data to the server using cgi-io
function upload_image(blob) {
	var upload_request = new XMLHttpRequest();
	var form_data  = new FormData();

	form_data.append("sessionid", data.ubus_rpc_session)
	form_data.append("filename", "/tmp/sysupgrade.bin")
	form_data.append("filemode", 755) // insecure?
	form_data.append("filedata", blob)

	upload_request.addEventListener('load', function(event) {
		// this checksum should be parsed
		document.getElementById("update_info").innerHTML = "flashing... please wait" // show fancy indicator http://www.ajaxload.info/
		ubus_request("attendedsysupgrade", "sysupgrade", '{  }', 'done');
  	});

  	upload_request.addEventListener('error', function(event) {
		document.getElementById("update_info").innerHTML = "uploading failed, please retry"
  	});

  	upload_request.open('POST', origin + '/cgi-bin/cgi-upload');
  	upload_request.send(form_data);
}

// download image from server once the url was received by image_request
function download_image(url) {
	console.log("download_image")
	document.getElementById("update_button").value = "flashing..."
	document.getElementById("update_button").disabled = true;
	var download_request = new XMLHttpRequest();
	download_request.open("GET", url);
	download_request.responseType = "arraybuffer";

	download_request.onload = function () {
		if (this.status === 200) {
			var blob = new Blob([download_request.response], {type: "application/octet-stream"});
			upload_image(blob)
		}
	};
	document.getElementById("update_info").innerHTML = "downloading image"
	download_request.send();
}

document.onload = setup()
</script>

<%+footer%>
